from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView

from AKapi.settings.const import *
from AKapi.utils.response import APIResponse
from rest_framework.response import Response
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import GenericViewSet


# class TestView(APIView):
#     def get(self, *args, **kwargs):
#         print(kwargs)
#         dic = {'name': 'AK'}
#         print('get.....')
#         # print(dic['age'])
#         return APIResponse()
#
#     def options(self, request, *args, **kwargs):
#         print('options....')
#         return APIResponse()
#
#     def post(self, *args, **kwargs):
#         print(kwargs)
#         dic = {'name': 'AK'}
#         print('post....')
#         # print(dic['age'])
#         # return APIResponse(headers={'Access-Control-Allow-Origin': 'http://127.0.0.1:8002', 'Access-Control-Allow-Headers': 'Content-Type'})
#         return APIResponse()
from home import models, serializer


# class BannerView(GenericAPIView, ListModelMixin):  # 路由配置 path('banner/', views.BannerView.as_view()),
# class BannerView(GenericViewSet, ListModelMixin):
# 路由配置用drf路由
# 缓存首页视图到Redis中
class BannerView(GenericViewSet, ListModelMixin):
    # 无论后边有多少数据要展示，只展示3条
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by('orders')[:BANNER_COUNTER]
    serializer_class = serializer.BannerModelSerializer

    def list(self, request, *args, **kwargs):

        # 把data的数据加缓存
        # 1.先去缓存中拿数据
        banner_list = cache.get('banner_list')
        if not banner_list:
            response = super().list(request, *args, **kwargs)  # 去数据库中拿轮播图数据
            print(response)
            print(response.data)
            cache.set('banner_list', response.data, 60 * 60 * 24)
            return response
        return Response(data=banner_list)

